<template>
  <el-dialog
    :title="title"
    :visible="accountFormVisible"
    :close-on-click-modal="false"
    @close="cancelAccountDialog('accountForm')"
    width="640px"
    custom-class="brand-dialog-min-width accountDialog oneColumnDialog"
    :modal-append-to-body="false"
  >
    <p class="warningInfo">
      <i class="el-icon-warning warningIcon"></i>
      <span class="warningText"
        >请添加授权项目使用的统一专户，仅可使用本专户供多个项目使用。</span
      >
    </p>
    <p class="warningInfo" v-show="isShowErrorMsg">
      <i class="el-icon-warning warningIcon"></i>
      <span class="warningText">{{ errorMsg }}</span>
    </p>
    <div style="padding: 24px 30px">
      <el-form
        :model="accountForm"
        :rules="formRules"
        ref="accountForm"
        label-width="120px"
      >
        <el-form-item label="区域：" prop="areaId">
          <el-cascader
            v-model="areaId"
            :options="areasOptions"
            class="optionWidth"
            @change="getAreaId"
            clearable
            filterable
            placeholder="请选择"
            :props="{ checkStrictly: true }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="开户银行：" prop="bankId">
          <el-select
            v-model="accountForm.bankId"
            placeholder="请选择"
            class="optionWidth"
            clearable
            filterable
            :disabled="isDisabled || accountForm.projectTotal > 0"
            @change="changeBankId"
          >
            <el-option
              v-for="(item, index) of bankOptions"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="银行网点：" prop="bankSiteId">
          <el-select
            v-model="accountForm.bankSiteId"
            class="optionWidth"
            :placeholder="
              accountForm.bankId != '' ? '请选择' : '请先选择开户银行'
            "
            clearable
            :disabled="isDisabled"
            filterable
          >
            <el-option
              v-for="(item, index) of bankBranchOptions"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专户账号：" prop="account">
          <el-input
            maxlength="64"
            v-model="accountForm.account"
            autocomplete="off"
            :disabled="isDisabled"
            placeholder="请输入专户账号"
            @blur="accountForm.account = changeValue($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="专户开户凭证：">
          <uploadAnnex
            :limitationFactor="limitationFactor"
            @getFile="getFile"
            :upLoadFile="accountForm.upLoadFileAcc"
          />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <uploadResult
              style="margin-left: 120px !important"
              :resultList="accountForm.upLoadFileAcc"
              @callBackResult="getFile"
            />
          </el-col>
        </el-row>
        <el-form-item label="农民工工资委托发放三方协议：" class="agreementBox">
          <uploadAnnex
            :limitationFactor="limitationFactorAgr"
            @getFile="getFileAgr"
            :upLoadFile="accountForm.upLoadAgreementFile"
          />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <uploadResult
              style="margin-left: 120px !important"
              :resultList="accountForm.upLoadAgreementFile"
              @callBackResult="getFileAgr"
            />
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click.native="cancelAccountDialog('accountForm')"
        class="cancel"
        >取消</el-button
      >
      <el-button
        type="primary"
        @click.native="saveBankInfo('accountForm')"
        class="save"
        :loading="saveLoading"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import common from '../../kits/common'
import { mapActions, mapState } from 'vuex'
export default {
  name: 'addAccountDialog',
  props: {
    accountFormVisible: {
      type: Boolean,
      default: false,
    },
    operationType: {
      type: String,
      default: '',
    },
    accountInfo: {
      type: Object,
      default() {
        return {}
      },
    },
    isDisabled: {
      type: Boolean,
      default: false,
    },
  },
  computed: { ...mapState(['areasOptions']) },
  data() {
    return {
      titlt: '', //标题信息
      // 补充专户信息
      accountForm: {
        // projectId: "",
        id: '',
        areaId: '',
        bankId: '', //银行id
        bankSiteId: '', //银行网点id
        account: '', //专户号
        upLoadFileAcc: [], //开户凭证
        upLoadAgreementFile: [], //三方协议
      },
      areaId: '',
      bankOptions: [], //银行列表
      bankBranchOptions: [], //银行网点
      formRules: {
        areaId: [
          {
            required: true,
            message: '区域不能为空',
            trigger: 'change',
          },
        ],
        bankId: [
          {
            required: true,
            message: '银行不能为空',
            trigger: 'change',
          },
        ],
        bankSiteId: [
          {
            required: true,
            message: '银行网点不能为空',
            trigger: 'change',
          },
        ],
        account: [
          {
            required: true,
            // pattern: /^([1-9]{1})(\d{11,18})((-)(\d{1,9}))*$/,
            pattern: /^[^\u4e00-\u9fa5]{0,}$/,
            message: '请输入正确格式的账号',
            trigger: 'blur',
          },
        ],
      },
      saveLoading: false, //专户保存按钮loading
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip:
          '请上传专户开户凭证，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
        messageFileSizetip: '最多能上传5M以内的附件',
      },
      limitationFactorAgr: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M”', //自定义报错提示语
        fileId: 'salaryExcelAgr', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'ExcelAgreement', //自定义id解决一个页面包含多个上传附件
        methodTip:
          '请上传农民工工资委托发放三方协议，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
        messageFileSizetip: '最多能上传5M以内的附件',
      },
      isShowErrorMsg: false,
      errorMsg: '',
    }
  },
  async created() {
    this.accountForm.id = this.accountInfo.id
    this.accountForm.account = this.accountInfo.account
    await this.getBank()
    if (this.operationType === 'updateAccount') {
      this.title = '修改工资专户信息'
      this.getAccountInfo()
    } else {
      this.title = '添加工资专户信息'
    }
  },
  methods: {
    ...mapActions(['getAreas']),
    //专户弹框取消
    cancelAccountDialog() {
      this.accountForm.upLoadFileAcc = []
      this.accountForm.upLoadAgreementFile = []
      this.accountForm.projectId = ''
      this.$refs.accountForm.resetFields()
      this.$emit('close-dialogStatus', false)
    },
    // 获取银行
    getBank() {
      var data = {
        type: 'BANK_TYPE',
      }
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: 'api-bs/base/dicitem/findbytype',
          data: data,
        })
          .then((response) => {
            resolve(response)
            this.bankOptions = response.data.result
          })
          .catch((error) => {
            reject(error)
            this.$message.error('数据获取失败')
          })
      })
    },
    // 更改银行获取银行网点
    changeBankId(val) {
      this.accountForm.bankSiteId = ''
      if (!val) {
        this.bankBranchOptions = []
      } else {
        this.getBankBranchList(val)
      }
    },
    // 获取银行网点
    getBankBranchList(bankId) {
      return new Promise((resolve, reject) => {
        this.axios
          .post('api-acc/accountbank/expand/banksite', { bankId })
          .then((res) => {
            resolve(res)
            this.bankBranchOptions = res.data.result
            if (res.data.result.length === 0) {
              this.$message({
                message: '请联系银行管理员进行网点信息维护',
                type: 'warning',
              })
            }
          })
          .catch((error) => {
            reject(error)
            this.$message({
              message: '获取网点数据失败',
              type: 'error',
            })
          })
      })
    },
    //保存专户信息
    saveBankInfo(formName) {
      this.saveLoading = true
      //确定按钮禁止点击
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            id: this.accountForm.id,
            areaId: this.accountForm.areaId,
            account: this.accountForm.account.replace(/\s+/g, ''),
            bankSiteId: this.accountForm.bankSiteId,
            bankId: this.accountForm.bankId,
            openCertificate: JSON.stringify(this.accountForm.upLoadFileAcc),
            agreement: JSON.stringify(this.accountForm.upLoadAgreementFile),
          }
          this.validAccountAjac(data)
        } else {
          this.saveLoading = false
          return false
        }
      })
    },
    validAccountAjac(data) {
      var url = 'api-acc/companyaccount/expand/addcompanyaccount'
      var confirmUrl = 'api-acc/companyaccount/expand/addcompanyaccountconfirm'

      if (this.operationType === 'updateAccount') {
        url = 'api-acc/companyaccount/expand/updatecompanymanyaccount'
        confirmUrl = 'api-acc/companyaccount/expand/updatecompanyaccountconfirm'
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then((res) => {
          this.saveLoading = false
          if (!res.data.hasError) {
            if (res.data.msgList && res.data.msgList.length > 0) {
              this.isShowErrorMsg = false
              this.$confirm(
                '企业中' +
                  res.data.msgList[0] +
                  '项目已绑定该专户，添加后将在企业统一专户中展示原有流水，项目端流水将被清空，是否确认？',
                '',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              )
                .then(() => {
                  this.saveAccountAjax(confirmUrl, data)
                })
                .catch(() => {})
            } else {
              this.$emit('close-dialogStatus', true) //关闭弹窗
            }
          } else {
            this.errorMsg = res.data.errorMsg
            this.isShowErrorMsg = true
          }
        })
        .catch((error) => {
          this.saveLoading = false
          this.$message({
            message: '请求失败',
            type: 'error',
          })
        })
    },
    //保存专户的ajax
    saveAccountAjax(url, data) {
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then((res) => {
          this.saveLoading = false
          if (!res.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$emit('close-dialogStatus', true) //关闭弹窗
          } else {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.saveLoading = false
          this.$message({
            message: '保存失败',
            type: 'error',
          })
        })
    },
    // 修改专户带出专户信息
    async getAccountInfo() {
      // 获取接收的专户信息
      //   let propsAccountInfo = JSON.parse(JSON.stringify(this.accountInfo));
      //   console.log("propsAccountInfo", propsAccountInfo);
      //   for (let i = 0; i < Object.keys(propsAccountInfo).length; i++) {
      //     if (
      //       Object.keys(propsAccountInfo)[i] === "bankId" &&
      //       propsAccountInfo[Object.keys(propsAccountInfo)[i]]
      //     ) {
      //       await this.getBankBranchList(
      //         propsAccountInfo[Object.keys(propsAccountInfo)[i]]
      //       );
      //     }
      //     if(Object.keys(propsAccountInfo)[i]==="areaId" && propsAccountInfo[Object.keys(propsAccountInfo)[i]]){
      //       this.areaId = propsAccountInfo[Object.keys(propsAccountInfo)[i]];
      //     }
      //   }
      //   // 上面代码异步请求接口以后再带入数据
      //   Object.keys(propsAccountInfo).forEach((v) => {
      //     this.accountForm[v] = propsAccountInfo[v];
      //   });
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/current',
        data: {
          account: this.accountForm.account,
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            let data = res.data.result
            this.accountForm = res.data.result
            // 子组件传值内容
            this.areaId = data.areaId
            this.accountForm.bankId = data.bankId
            this.accountForm.bankSiteId = data.bankSiteId
            this.accountForm.account = data.account
            this.accountForm.upLoadFileAcc = data.openCertificateFiles
            this.accountForm.upLoadAgreementFile = data.agreementFiles
            this.getBankBranchList(data.bankId)
          } else {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('专户数据获取失败')
        })
    },
    getFile(val) {
      this.accountForm.upLoadFileAcc = val
    },
    getFileAgr(val) {
      this.accountForm.upLoadAgreementFile = val
    },
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.accountForm.areaId = areaId
    },
  },
}
</script>

<style scoped lang="less">
// 修改专户弹窗样式
.uploadBox {
  position: relative;
  .uploadImg {
    width: 96px;
    height: 40px;
    color: #009588;
    border: 1px solid #009588;
    cursor: pointer;
  }
  .upLoadDom {
    position: absolute;
    width: 96px;
    height: 40px;
    top: 0;
    left: 0;
    opacity: 0;
    line-height: 0px;
    form {
      input {
        width: 96px;
        height: 40px;
        line-height: 0px;
        cursor: pointer;
      }
    }
  }
}

.agreementBox {
  /deep/label {
    line-height: 20px;
  }
}
.imgStyle {
  margin-left: 135px;
  li {
    position: relative;
    margin-right: 20px;
    margin-bottom: 20px;
    .iconjian {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
      cursor: pointer;
    }
    .el-image {
      cursor: pointer;
    }
  }
}
.optionWidth,
.inputWidth {
  width: 310px !important;
}
.warningInfo {
  background: #fffbe6;
  height: 36px;
  padding-left: 48px;
  position: relative;
  .warningIcon {
    color: orange;
    font-size: 20px;
    position: absolute;
    top: 8px;
    left: 20px;
  }
  .warningText {
    font-family: 'SourceHanSansCN-Regular';
    font-size: 14px;
    color: #ff4d4a;
    line-height: 36px;
  }
}
/deep/ .el-dialog__body {
  padding: 0;
}
/deep/ .el-dialog__title {
  font-family: SourceHanSansCN-Regular;
  font-size: 18px;
  color: #424242;
}
</style>
